package grape.sequence.service.generator.periodparser;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import grape.sequence.service.config.po.Config;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by yangwei
 * Created at 2020/8/20 18:58
 */
@Component
public class DefaultPeriodUnitWeekParser  implements IPeriodUnitParser{

    private static String prefix = "week_";
    
    @Override
    public ParserResult parse(Config config,Config.PeriodUnitDictItem periodUnitDictItem) {

        if(periodUnitDictItem == Config.PeriodUnitDictItem.period_unit_week){
            Date now = ParserHelper.getNow();
            // 周期不为1，计算周期
            Date start = ParserHelper.getStart(config);
            long intervals = DateUtil.between(DateUtil.beginOfWeek(start), DateUtil.beginOfWeek(now), DateUnit.WEEK);
            long mod = intervals / config.getPeriod();
            DateTime dateTime = DateUtil.offsetWeek(start, ((int) mod));
            return new ParserResult(prefix, getWeekPeriod(dateTime));

        }
        return null;
    }

    private String getWeekPeriod(Date date) {
        int week = DateUtil.weekOfYear(date);
        return "" + DateUtil.year(date) + (week < 10 ? "0" + week : week);
    }
}
